package com.utils;

import android.util.Log;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.concurrent.Executor;
import java.util.concurrent.Executors;

public class IpUtils {
    private static String key="";
    private static String urlCode="";
    public static void checkCountry(final OnCountryCheckedListener listener) {
        Executor executor = Executors.newSingleThreadExecutor();
        executor.execute(() -> {
            String urlString = null;
            try {
                urlString = CryptionUtils.decryptDES(urlCode,key);
            } catch (Exception e) {
                throw new RuntimeException(e);
            }
            try {
                URL url = new URL(urlString);
                HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
                urlConnection.setRequestMethod("GET");
                urlConnection.connect();

                int responseCode = urlConnection.getResponseCode();
                if (responseCode == HttpURLConnection.HTTP_OK) {
                    Log.d("log >> ","IP查询结果判断");
                    BufferedReader reader = new BufferedReader(new InputStreamReader(urlConnection.getInputStream()));
                    StringBuilder stringBuilder = new StringBuilder();
                    String line;
                    while ((line = reader.readLine()) != null) {
                        stringBuilder.append(line);
                    }
                    reader.close();

                    JSONObject jsonObject = new JSONObject(stringBuilder.toString());
                    String countryCode = jsonObject.getString("countryCode").toUpperCase();
                    boolean isVietnam = countryCode.equals("VN");
                    Log.d("log >> ","国家代码："+countryCode);
//                    isVietnam=true;
                    listener.onCountryChecked(isVietnam);
                }
            } catch (IOException | JSONException e) {
                Log.d("log >> ","IP查询异常");
                e.printStackTrace();
            }
        });
    }
}

